package com.example.lt.handler;

import com.example.lt.exception.BaseException;
import com.example.lt.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.StringJoiner;

/**
 * @Author 小涛Tao
 * @Date: 2024/07/28/11:48
 * version 1.0 注释：全局异常处理器，处理项目中抛出的异常
 **/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Result ex(Exception e){
        e.printStackTrace();
        String msg = ObjectUtils.isEmpty(e.getMessage()) ? e.toString() : e.getMessage();
        return Result.error().message(msg);
    }

    @ExceptionHandler(BaseException.class)
    public Result bex(BaseException e){
        return Result.error().message(e.getMsg());
    }


    // 数据校验异常处理，比如方法中的参数进行 @Validated 校验有异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result exception(MethodArgumentNotValidException e) {
        // e.getBindingResult()：获取BindingResult
        BindingResult bindingResult = e.getBindingResult();
        // 收集数据校验失败后的信息
        StringJoiner joiner = new StringJoiner(",");

        bindingResult.getFieldErrors().stream().forEach((fieldError) -> {
            joiner.add(fieldError.getDefaultMessage());

        });
        return Result.error().message(joiner.toString());
    }

}
